<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI功能演示页面</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Microsoft YaHei', sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
        }
        .card {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 20px;
            padding: 30px;
            margin-bottom: 20px;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
        }
        h1 {
            color: #2c3e50;
            margin-bottom: 10px;
        }
        h2 {
            color: #2c3e50;
            margin-bottom: 15px;
            font-size: 20px;
        }
        .muted {
            color: #7f8c8d;
            margin-bottom: 20px;
            font-size: 14px;
        }
        .input-group {
            margin-bottom: 15px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            color: #2c3e50;
            font-weight: 500;
        }
        input, textarea, select {
            width: 100%;
            padding: 12px;
            border: 2px solid #e9ecef;
            border-radius: 10px;
            font-size: 14px;
            font-family: inherit;
            transition: border-color 0.3s;
        }
        input:focus, textarea:focus, select:focus {
            outline: none;
            border-color: #667eea;
        }
        textarea {
            min-height: 100px;
            resize: vertical;
        }
        button {
            padding: 12px 24px;
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
            border: none;
            border-radius: 10px;
            font-size: 15px;
            font-weight: 600;
            cursor: pointer;
            transition: transform 0.3s, box-shadow 0.3s;
        }
        button:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 20px rgba(102, 126, 234, 0.4);
        }
        button:active {
            transform: translateY(0);
        }
        .output {
            background: #f8f9fa;
            border: 2px solid #e9ecef;
            border-radius: 10px;
            padding: 15px;
            margin-top: 15px;
            white-space: pre-wrap;
            font-family: 'Courier New', monospace;
            font-size: 13px;
            color: #2c3e50;
            max-height: 400px;
            overflow-y: auto;
        }
        .chat-container {
            border: 2px solid #e9ecef;
            border-radius: 10px;
            padding: 15px;
            margin-top: 15px;
            max-height: 400px;
            overflow-y: auto;
            background: #f8f9fa;
        }
        .message {
            margin-bottom: 15px;
            padding: 10px;
            border-radius: 8px;
        }
        .message.user {
            background: #667eea;
            color: white;
            text-align: right;
        }
        .message.assistant {
            background: #e9ecef;
            color: #2c3e50;
        }
        .loading {
            color: #667eea;
            font-style: italic;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="card">
            <h1>🤖 AI功能演示页面</h1>
            <p class="muted">这个页面展示了如何通过Python后端调用AI功能</p>
        </div>

        <!-- 1. 基础AI问答 -->
        <div class="card">
            <h2>1. 基础AI问答 (/api/ai)</h2>
            <p class="muted">单次问答，支持上下文</p>
            <div class="input-group">
                <label>问题：</label>
                <textarea id="question-input" placeholder="请输入您的问题..."></textarea>
            </div>
            <div class="input-group">
                <label>上下文（可选）：</label>
                <textarea id="context-input" placeholder="可选的上下文信息..."></textarea>
            </div>
            <button onclick="askAI()">发送问题</button>
            <div class="output" id="ai-output"></div>
        </div>

        <!-- 2. AI聊天对话 -->
        <div class="card">
            <h2>2. AI聊天对话 (/api/ai_chat)</h2>
            <p class="muted">支持多轮对话，自动维护对话历史</p>
            <div class="input-group">
                <label>消息：</label>
                <input type="text" id="chat-input" placeholder="输入消息..." onkeypress="if(event.key==='Enter') chatWithAI()">
            </div>
            <button onclick="chatWithAI()">发送消息</button>
            <div class="chat-container" id="chat-container"></div>
        </div>

        <!-- 3. AI智能分诊 -->
        <div class="card">
            <h2>3. AI智能分诊 (/api/triage)</h2>
            <p class="muted">根据症状推荐就诊科室</p>
            <div class="input-group">
                <label>症状描述：</label>
                <textarea id="symptoms-input" placeholder="例如：头痛、发热、咳嗽三天"></textarea>
            </div>
            <button onclick="triage()">智能分诊</button>
            <div class="output" id="triage-output"></div>
        </div>

        <!-- 4. AI报告解读 -->
        <div class="card">
            <h2>4. AI报告解读 (/api/report_explain)</h2>
            <p class="muted">解读医疗检查报告</p>
            <div class="input-group">
                <label>报告内容：</label>
                <textarea id="report-input" placeholder="请输入检查报告内容..."></textarea>
            </div>
            <button onclick="explainReport()">解读报告</button>
            <div class="output" id="report-output"></div>
        </div>

        <!-- 5. AI健康风险评估 -->
        <div class="card">
            <h2>5. AI健康风险评估 (/api/health_risk)</h2>
            <p class="muted">评估个人健康风险</p>
            <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 15px;">
                <div class="input-group">
                    <label>年龄：</label>
                    <input type="number" id="age-input" placeholder="45">
                </div>
                <div class="input-group">
                    <label>性别：</label>
                    <select id="gender-input">
                        <option value="男">男</option>
                        <option value="女">女</option>
                    </select>
                </div>
                <div class="input-group">
                    <label>身高（cm）：</label>
                    <input type="number" id="height-input" placeholder="175">
                </div>
                <div class="input-group">
                    <label>体重（kg）：</label>
                    <input type="number" id="weight-input" placeholder="75">
                </div>
                <div class="input-group">
                    <label>血压：</label>
                    <input type="text" id="bp-input" placeholder="130/85">
                </div>
                <div class="input-group">
                    <label>血糖（mmol/L）：</label>
                    <input type="number" step="0.1" id="bs-input" placeholder="6.5">
                </div>
            </div>
            <div class="input-group">
                <label>生活习惯：</label>
                <input type="text" id="habits-input" placeholder="偶尔吸烟">
            </div>
            <div class="input-group">
                <label>既往病史：</label>
                <input type="text" id="history-input" placeholder="高血压">
            </div>
            <button onclick="assessHealth()">评估健康风险</button>
            <div class="output" id="health-output"></div>
        </div>
    </div>

    <script>
        let chatThreadId = null;
        let chatHistory = [];

        // 1. 基础AI问答
        async function askAI() {
            const question = document.getElementById('question-input').value.trim();
            const context = document.getElementById('context-input').value.trim();
            const output = document.getElementById('ai-output');
            
            if (!question) {
                output.textContent = '请输入问题！';
                return;
            }
            
            output.textContent = '正在思考...';
            
            try {
                const response = await fetch('/api/ai', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ question, context })
                });
                const data = await response.json();
                
                if (data.ok) {
                    output.textContent = `问题：${question}\n\n${context ? '上下文：' + context + '\n\n' : ''}AI回答：\n${data.answer}`;
                } else {
                    output.textContent = `错误：${data.error || '未知错误'}`;
                }
            } catch (error) {
                output.textContent = `网络错误：${error.message}`;
            }
        }

        // 2. AI聊天对话
        async function chatWithAI() {
            const input = document.getElementById('chat-input');
            const message = input.value.trim();
            const container = document.getElementById('chat-container');
            
            if (!message) return;
            
            // 添加用户消息
            addMessage('user', message);
            input.value = '';
            
            // 显示加载状态
            const loadingMsg = addMessage('assistant', '正在思考...', true);
            
            try {
                const response = await fetch('/api/ai_chat', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        thread_id: chatThreadId,
                        message: message
                    })
                });
                const data = await response.json();
                
                // 移除加载消息
                loadingMsg.remove();
                
                if (data.ok) {
                    chatThreadId = data.thread_id;
                    addMessage('assistant', data.answer);
                } else {
                    addMessage('assistant', `错误：${data.error || '未知错误'}`);
                }
            } catch (error) {
                loadingMsg.remove();
                addMessage('assistant', `网络错误：${error.message}`);
            }
        }

        function addMessage(role, content, isLoading = false) {
            const container = document.getElementById('chat-container');
            const div = document.createElement('div');
            div.className = `message ${role} ${isLoading ? 'loading' : ''}`;
            div.textContent = content;
            container.appendChild(div);
            container.scrollTop = container.scrollHeight;
            return div;
        }

        // 3. AI智能分诊
        async function triage() {
            const symptoms = document.getElementById('symptoms-input').value.trim();
            const output = document.getElementById('triage-output');
            
            if (!symptoms) {
                output.textContent = '请输入症状描述！';
                return;
            }
            
            output.textContent = '正在分析...';
            
            try {
                const response = await fetch('/api/triage', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ symptoms })
                });
                const data = await response.json();
                
                if (data.ok) {
                    output.textContent = `症状：${symptoms}\n\n推荐科室：${data.department}\n可能的问题：${data.candidates?.join('、') || '待确认'}\n\nAI分析：\n${data.ai}`;
                } else {
                    output.textContent = `错误：${data.error || '未知错误'}`;
                }
            } catch (error) {
                output.textContent = `网络错误：${error.message}`;
            }
        }

        // 4. AI报告解读
        async function explainReport() {
            const text = document.getElementById('report-input').value.trim();
            const output = document.getElementById('report-output');
            
            if (!text) {
                output.textContent = '请输入报告内容！';
                return;
            }
            
            output.textContent = '正在解读...';
            
            try {
                const response = await fetch('/api/report_explain', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ text })
                });
                const data = await response.json();
                
                if (data.ok) {
                    output.textContent = `报告内容：\n${text}\n\n关键提示：\n${data.hints?.join('\n') || '无'}\n\n详细解读：\n${data.ai}`;
                } else {
                    output.textContent = `错误：${data.error || '未知错误'}`;
                }
            } catch (error) {
                output.textContent = `网络错误：${error.message}`;
            }
        }

        // 5. AI健康风险评估
        async function assessHealth() {
            const output = document.getElementById('health-output');
            
            const payload = {
                age: parseInt(document.getElementById('age-input').value) || 0,
                gender: document.getElementById('gender-input').value || '',
                height: parseFloat(document.getElementById('height-input').value) || 0,
                weight: parseFloat(document.getElementById('weight-input').value) || 0,
                blood_pressure: document.getElementById('bp-input').value || '',
                blood_sugar: parseFloat(document.getElementById('bs-input').value) || 0,
                habits: document.getElementById('habits-input').value || '',
                medical_history: document.getElementById('history-input').value || ''
            };
            
            if (!payload.age || !payload.height || !payload.weight) {
                output.textContent = '请填写至少年龄、身高、体重！';
                return;
            }
            
            output.textContent = '正在评估...';
            
            try {
                const response = await fetch('/api/health_risk', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(payload)
                });
                const data = await response.json();
                
                if (data.ok) {
                    output.textContent = `健康信息：\n年龄：${payload.age}岁，性别：${payload.gender}\n身高：${payload.height}cm，体重：${payload.weight}kg\n血压：${payload.blood_pressure}，血糖：${payload.blood_sugar}mmol/L\n生活习惯：${payload.habits}\n既往病史：${payload.medical_history}\n\n风险评估：\n风险等级：${data.risk_level}\n风险项：${data.risks?.join('、') || '无'}\n建议：${data.suggestions?.join('、') || '无'}\n\nAI详细分析：\n${data.ai}`;
                } else {
                    output.textContent = `错误：${data.error || '未知错误'}`;
                }
            } catch (error) {
                output.textContent = `网络错误：${error.message}`;
            }
        }
    </script>
</body>
</html>

